<?php

namespace app\admin\controller\general;

use app\admin\model\Admin;
use app\common\controller\Backend;
use fast\Random;
use think\Session;
use think\Validate;
use think\Db;
use think\Log;

/**
 * 运营配置
 *
 * @icon fa fa-user
 */
class Operate extends Backend
{

    /**
     * 查看
     */
    public function index()
    {
        //其他配置
        $config = [];
        $configs = db('configs')->where('status', 0)->field('type,field,value,group')->select();
        foreach ($configs as $v) {
            $config[$v['type']][$v['group']][$v['field']] = $v['value'];
        }
        foreach ($config as $k => $v) {
            $this->assign($k, $v);
        }

        //轮播图
        $banner_config = db('banner')->where('status', 0)->field('id,url,item_url,sort')->select();
        $this->assign('banner', $banner_config);
        return view();
    }

    /**
     * 更新信息
     */
    public function update()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            $params = array_filter(array_intersect_key(
                $params,
                array_flip(array('email', 'nickname', 'password', 'avatar'))
            ));
            unset($v);
            if (!Validate::is($params['email'], "email")) {
                $this->error(__("Please input correct email"));
            }
            if (isset($params['password'])) {
                if (!Validate::is($params['password'], "/^[\S]{6,16}$/")) {
                    $this->error(__("Please input correct password"));
                }
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            }
            $exist = Admin::where('email', $params['email'])->where('id', '<>', $this->auth->id)->find();
            if ($exist) {
                $this->error(__("Email already exists"));
            }
            if ($params) {
                $admin = Admin::get($this->auth->id);
                $admin->save($params);
                //因为个人资料面板读取的Session显示，修改自己资料后同时更新Session
                Session::set("admin", $admin->toArray());
                $this->success();
            }
            $this->error();
        }
        return;
    }

    /**
     * 保存服务条款和隐私政策
     */
    public function savePrivacy(){
        $data = input('post.privacy/a');
        if(empty($data)){
            $this->success();
        }
        Db::startTrans();
        try{
            $res = 1;
            foreach ($data as $k => $v) {
                $old = db('configs')->where(['type' => 'privacy', 'group' => $k, 'status' => 0])->column('value','field');
                foreach ($v as $key => $val) {
                    if($old[$key] != $val){
                        $res = $res && db('configs')->where(['type' => 'privacy', 'group' => $k, 'field' => $key, 'status' => 0])->update(['value' => $val, 'updatetime' => time()]);
                    }
                }
            }
            if(!$res){
                exception('保存失败');
            }
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }

     /**
     * 保存轮播图
     */
    public function saveBanner(){
        $ids = [];
        $data = input('post.banner/a');
        if(empty($data)){
            $this->success();
        }
        Db::startTrans();
        try{
            $res = 1;
            foreach ($data as $k => $v) {
                if($v['id']){
                    $update = [
                        'url' => $v['url'],
                        'item_url' => $v['item_url'],
                        'sort' => $v['sort'],
                        'updatetime' => time()
                    ];
                    $res = $res && db('banner')->where('id', $v['id'])->update($update);
                } else {
                    $insert = [
                        'url' => $v['url'],
                        'item_url' => $v['item_url'],
                        'sort' => $v['sort'],
                        'createtime' => time()
                    ];
                    $id = db('banner')->insertGetId($insert);
                    $ids[] = ['idx' => (int)$k + 1, 'id' => $id];
                    $res = $res && $id;
                }
            }
            if(!$res){
                exception('保存失败');
            }
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('保存成功','',$ids);
    }

    
}
